var schoolID;
var tbl_students_obj;
var studentStandardSelected;
var studentDivisionSelected;

$(document).ready(function (){
	//cookie values
	var cookieValue=$.cookie("school");
	var cookieValueArray = cookieValue.split('/');
	schoolID = cookieValueArray[0];
	
	tbl_students_obj=$('#tbl-student-students').dataTable(
		{
			"columnDefs": [
				{
					"targets": [ 0 ],
					"visible": false,
					"searchable": false
				}
			]
		}
	);
	
});

function students() {
	
	$('#student_standard').empty();
	$('#student_division').empty();
	studentStandardSelected="";
	studentDivisionSelected="";
	
	var url="php/getStandard.php";
		 
	$.ajax({
	url: url,
	type: 'GET',
	dataType: "json",
	data: 'school_id='+schoolID,
	success: function(data) {
		if(data.error=="false")
		{
			for(var x=0;x<(data.list.length);x++)
			{				 
				 $("#student_standard").append("<li><a onclick=\"studentStandardOnClick(this)\" value=\""+data.list[x].id+"\">"+data.list[x].name+"</a></li>");
			}		
		}
	},
	error: function(e) {
		console.debug("error");
	}
	});
}

function studentStandardOnClick(anchor) {
    studentStandardSelected = anchor.getAttribute('value'); 
    var url="php/getDivision.php"; 
    
    $('#student_division').empty();
		 
	$.ajax({
	url: url,
	type: 'GET',
	dataType: "json",
	data: 'standard_id='+studentStandardSelected,
	success: function(data) {
		if(data.error=="false")
		{
			for(var x=0;x<(data.list.length);x++)
			{				 
				 $("#student_division").append("<li><a onclick=\"studentDivisionOnClick(this)\" value=\""+data.list[x].id+"\">"+data.list[x].name+"</a></li>");
			}		
		}
	},
	error: function(e) {
		console.debug("error");
	}
	});
}

function studentDivisionOnClick(anchor) {
	studentDivisionSelected = anchor.getAttribute('value');
	studentTableData();
}

function studentTableData()
{
    var url="php/getStudent.php";
	tbl_students_obj.fnClearTable();
		
	$.ajax({
	url: url,
	type: 'GET',
	dataType: "json",
	data: 'standard_id='+studentStandardSelected+'&division_id='+studentDivisionSelected,
	success: function(data) {
		if(data.error=="false")
		{
			for(var x=0;x<(data.list.length);x++)
			{	
				tbl_students_obj.fnAddData([
				data.list[x].id,
				data.list[x].roll_number,
				data.list[x].name,
				data.list[x].gender,
				data.list[x].email,
				data.list[x].cell_number,
				'<center><button class=\"btn btn-warning btn-xs\" onclick=\"sendemail(\''+data.list[x].id+'\')\"><span class=\"glyphicon glyphicon-envelope\"></span></button><center>',
				'<center><button class="btn btn-info btn-xs" data-toggle="tooltip" data-placement="top" title="Edit Record" id="studentEdit"> <span class="glyphicon glyphicon-pencil"></span> </button> <button class="btn btn-danger btn-xs" onclick="deleteStudent(' +data.list[x].id+ ')" data-toggle="tooltip" data-placement="top" title="Delete Record"> <span class="glyphicon glyphicon-trash"></span> </button></center>'				
				]);
			}		
		}
	},
	error: function(e) {
		console.debug("error");
	}
	});
}

function submitStudent()
{
	var studentRollno = $('#studentRollno').val();
	var studentName = $('#studentName').val();
	var studentGender = $('#studentGender').val();
	var studentEmail = $('#studentEmail').val();
	var studentPhone = $('#studentPhone').val();
		
	if(studentRollno == "" || studentName == "" || studentGender == "" || studentEmail == "" || studentPhone == "" || typeof studentStandardSelected === "undefined" || typeof studentDivisionSelected === "undefined")
		return;
	
	var data = {
		"roll_number": studentRollno,
		"name": studentName,
		"gender": studentGender,
		"email": studentEmail,
		"cell_number": studentPhone,
		"standard_id": studentStandardSelected,
		"division_id": studentDivisionSelected,
		"school_id": schoolID
	}; 
		
	var url;
	if(document.domain=="localhost")
	{
		url="http://localhost/lifeinclass/php/student.php";
	}else{
		url="php/student.php";
	}
	
	$.ajax({
	type: "POST",
	dataType: "json",
	url: url, 
	data: data,
	success: function(data) {
		if(data.error == "false"){
			$('#studentRollno').val("");
			$('#studentName').val("");
			$('#studentGender').val("");
			$('#studentEmail').val("");
			$('#studentPhone').val("");
			studentTableData();
		}
	},
	error: function(e) {
		console.debug(e);
	}
	}); 
	
}

var previousTr;
$('#tbl-student-students tbody').on('click',"button",function() {
    var nTr = $(this).parents('tr');
	var id = this.id;
	
    if(id == 'studentEdit')
    {
		/*
		if(typeof previousTr != "undefined"){
			if (tbl_students_obj.fnIsOpen(previousTr)  && previousTr != nTr) {
				tbl_students_obj.fnClose(previousTr);
			}
		}
		*/
        
		if ( tbl_students_obj.fnIsOpen(nTr) )
		{
			tbl_students_obj.fnClose( nTr );
			$('#tbl-student-students').addClass('table-hover');
		}
		else
		{
			tbl_students_obj.fnOpen( nTr, fnFormatStudentDetails( tbl_students_obj , nTr), 'details' );
			$('#tbl-student-students').removeClass('table-hover');
			previousTr = nTr;
		}
	}
});

$('#tbl-student-students').on( 'click', 'tr',function(){
		/*
		var nTr = $(this);
		
		if ( tbl_students_obj.fnIsOpen(nTr) )
        {
            tbl_students_obj.fnClose( nTr );
            $('#tbl-student-students').addClass('table-hover');
        }
        */
	});

var studentRowId;
function fnFormatStudentDetails(table,row){
	var oData = tbl_students_obj.fnGetData( row );
	studentRowId = oData[0];	
	var out;
	var url="php/getStudentDetail.php";
			
	$.ajax({
	url: url,
	type: 'GET',
	dataType: "json",
	data: 'id='+studentRowId,
	success: function(data) {
		if(data.error=="false")
		{			
			$('#roll_number'+studentRowId).val(data.list.roll_number);
			$('#name'+studentRowId).val(data.list.name);
			$('#gender'+studentRowId).val(data.list.gender);
			$('#blood'+studentRowId).val(data.list.blood);
			$('#standard_id'+studentRowId).val(data.list.standard_id);
			$('#division_id'+studentRowId).val(data.list.division_id);
			$('#height'+studentRowId).val(data.list.height);
			$('#weight'+studentRowId).val(data.list.weight);
			$('#father_name'+studentRowId).val(data.list.father_name);
			$('#father_qualification'+studentRowId).val(data.list.father_qualification);
			$('#father_occupation'+studentRowId).val(data.list.father_occupation);
			$('#mother_name'+studentRowId).val(data.list.mother_name);
			$('#mother_qualification'+studentRowId).val(data.list.mother_qualification);
			$('#mother_occupation'+studentRowId).val(data.list.mother_occupation);
			$('#guardian_name'+studentRowId).val(data.list.guardian_name);
			$('#guardian_qualification'+studentRowId).val(data.list.guardian_qualification);
			$('#guardian_occupation'+studentRowId).val(data.list.guardian_occupation);
			$('#city'+studentRowId).val(data.list.city);
			$('#district'+studentRowId).val(data.list.district);
			$('#state'+studentRowId).val(data.list.state);
			$('#village'+studentRowId).val(data.list.village);
			$('#landline'+studentRowId).val(data.list.landline);
			$('#cell_number'+studentRowId).val(data.list.cell_number);
			$('#email'+studentRowId).val(data.list.email);
			$('#address'+studentRowId).val(data.list.address);
						
			if(data.list.image)
				$('#image'+studentRowId).attr('src', data.list.image);
		}
	},
	error: function(e) {
		console.debug("error");
	}
	});
	
	
	out = 	'<div style="border: 1px solid #ddd; padding:10px;">'+
					'<div role="tabpanel">'+
						'<ul class="nav nav-tabs" role="tablist">'+
				    		'<li role="presentation" class="active"><a href="#studentntdetails" aria-controls="home" role="tab" data-toggle="tab">Student Details</a></li>'+
					    	'<li role="presentation"><a href="#parentdetails" aria-controls="profile" role="tab" data-toggle="tab">Parent Details</a></li>'+
					    	'<li role="presentation"><a href="#contactdetails" aria-controls="messages" role="tab" data-toggle="tab">Contact Details</a></li>'+
					  	'</ul>'+
					  	'<div class="tab-content">'+
				    		'<div role="tabpanel" class="tab-pane fade in active" id="studentntdetails">'+
				    			'<div class="row">'+
								    '<div class="col-md-3"><img width="70%" src="images/default_user.png" style="margin: auto;border: 1px solid #ddd;box-shadow: 0px 0px 5px 0px;border-radius: 10px;margin: 15%"  id="image'+studentRowId+'">'+'<input type="file" onchange="fileinputStudents(\'imageInput'+studentRowId+'\','+studentRowId+');" id="imageInput'+studentRowId+'"></div>'+
								    '<div class="col-md-9">'+
								      	'<div class="row" style="margin-top: 5%">'+
									      	'<div class="col-md-5">'+
									      		'<input type="text" style="margin-bottom:4%" placeholder="Roll No." class="form-control" id="roll_number'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Full Name" class="form-control" id="name'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Gender" class="form-control" id="gender'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Blood Group" class="form-control" id="blood'+studentRowId+'">'+
											'</div>'+
											'<div class="col-md-5">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Standard" class="form-control" id="standard_id'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Division" class="form-control" id="division_id'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Height" class="form-control" id="height'+studentRowId+'">'+
												'<input type="text" style="margin-bottom:4%" placeholder="Weight" class="form-control" id="weight'+studentRowId+'">'+
											'</div>'+
										'</div>'+
								    '</div>'+
								'</div>'+
					    	'</div>'+
						    '<div role="tabpanel" class="tab-pane fade" id="parentdetails">'+
						    	'<div class="row" style="margin-top: 3%">'+
								    '<div class="col-md-4">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Father Name" class="form-control" id="father_name'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Qualification" class="form-control" id="father_qualification'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Occupation" class="form-control" id="father_occupation'+studentRowId+'">'+									
									'</div>'+
								    '<div class="col-md-4">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Mother Name" class="form-control" id="mother_name'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Qualification" class="form-control" id="mother_qualification'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Occupation" class="form-control" id="mother_occupation'+studentRowId+'">'+
									'</div>'+
									'<div class="col-md-4">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="Guardian Name" class="form-control" id="guardian_name'+studentRowId+'">'+
										'<input type="text" style="margin-bottom:4%" placeholder="Relationship With Student" class="form-control" id="guardian_qualification'+studentRowId+'">'+
										'<input type="text" style="margin-bottom:4%" placeholder="Occupation" class="form-control" id="guardian_occupation'+studentRowId+'">'+
									'</div>'+
								'</div>'+
						    '</div>'+
						    '<div role="tabpanel" class="tab-pane fade" id="contactdetails">'+
						    	'<div class="row" style="margin-top: 3%">'+
						    	    '<div class="col-md-4">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="City" class="form-control" id="city'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="District" class="form-control" id="district'+studentRowId+'">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="State" class="form-control" id="state'+studentRowId+'">'+
								    '</div>'+
								    '<div class="col-md-4">'+
										'<input type="text" style="margin-bottom:4%" placeholder="Village" class="form-control" id="village'+studentRowId+'">'+
										'<input type="text" style="margin-bottom:4%" placeholder="Land Phone" class="form-control" id="landline'+studentRowId+'">'+
										'<input type="text" style="margin-bottom:4%" placeholder="Cell Phone" class="form-control" id="cell_number'+studentRowId+'">'+
								    '</div>'+
								    '<div class="col-md-4">'+
								    	'<input type="text" style="margin-bottom:4%" placeholder="E-mail" class="form-control" id="email'+studentRowId+'">'+
										'<textarea name="inputtext" placeholder="Residential Address" id="address'+studentRowId+'">'+
								    	'</textarea>'+
								    '</div>'+
								'</div>'+
						    '</div>'+
						    '<div class="row"><button type="button" class="btn btn-success" style="float:right;margin-right:150px;" onclick="saveStudent('+studentRowId+')">Save</button></div>'+
					  	'</div>'+
				  	'</div>'+
				'</div>';
	return out;
}

var uploadedStudentImage;
function fileinputStudents(id,studentId)
{
	var uploadImage = jQuery('#'+id).get(0).files[0];
	
	var reader = new FileReader();
	reader.readAsDataURL(uploadImage);
	reader.onload = shipOff;
	function shipOff(event) {
		uploadedStudentImage = event.target.result;		
		$("#image"+studentId).attr("src", uploadedStudentImage);
	}	
}

function saveStudent(id)
{
	var data = {
		"id":id,
		"roll_number": $('#roll_number'+id).val(), 
		"name": $('#name'+id).val(),
		"gender": $('#gender'+id).val(),
		"blood": $('#blood'+id).val(),
		//"standard_id": $('#standard_id'+id).val(),
		//"division_id": $('#division_id'+id).val(),
		"height": $('#height'+id).val(),
		"weight": $('#weight'+id).val(),
		"father_name": $('#father_name'+id).val(),
		"father_qualification": $('#father_qualification'+id).val(),
		"father_occupation": $('#father_occupation'+id).val(),
		"mother_name": $('#mother_name'+id).val(),
		"mother_qualification": $('#mother_qualification'+id).val(),
		"mother_occupation": $('#mother_occupation'+id).val(),
		"guardian_name": $('#guardian_name'+id).val(),
		"guardian_qualification": $('#guardian_qualification'+id).val(),
		"guardian_occupation": $('#guardian_occupation'+id).val(),
		"city": $('#city'+id).val(),
		"district": $('#district'+id).val(),
		"state": $('#state'+id).val(),
		"village": $('#village'+id).val(),
		"landline": $('#landline'+id).val(),
		"cell_number": $('#cell_number'+id).val(),
		"email": $('#email'+id).val(),
		"address": $('#address'+id).val(),
		"image":uploadedStudentImage
	}; 
	
	var url;
	if(document.domain=="localhost")
	{
		url="http://localhost/lifeinclass/php/updateStudent.php";
	}else{
		url="php/updateStudent.php";
	}
	
	$.ajax({
	type: "POST",
	dataType: "json",
	url: url, 
	data: data,
	success: function(data) {
		if(data.error == "false"){			
			studentTableData();
		}
	},
	error: function(e) {
		console.debug(e);
	}
	}); 
	
}

function deleteStudent(id)
{
	var data = {
		"id": id
	}; 
		
	var url;
	if(document.domain=="localhost")
	{
		url="http://localhost/lifeinclass/php/deleteStudent.php";
	}else{
		url="php/deleteStudent.php";
	}
	
	$.ajax({
	type: "POST",
	dataType: "json",
	url: url, 
	data: data,
	success: function(data) {
		if(data.error == "false"){
			studentTableData();
		}
	},
	error: function(e) {
		console.debug(e);
	}
	}); 
}

function sendemail(id)
{
	var data = {
		"id": id
	}; 
		
	var url;
	if(document.domain=="localhost")
	{
		url="http://localhost/lifeinclass/php/studentInviteEmail.php";
	}else{
		url="php/studentInviteEmail.php";
	}
	
	$.ajax({
	type: "POST",
	dataType: "json",
	url: url, 
	data: data,
	success: function(data) {
		if(data.error == "false"){
			
		}
	},
	error: function(e) {
		console.debug(e);
	}
	}); 
}
